<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/25 0025
 * Time: 14:11
 */

namespace app\pay\controller;


use app\jointly\controller\Base;
use think\Cache;
use think\Db;
use think\Log;
use Yansongda\Pay\Pay;

class Back extends Base
{

    //todo 支付宝
    protected static $alipay = [
        'app_id'            => '2018121962575627',     //todo appid
        'notify_url'        => 'http://www.aibinance.com/public/index.php/zfbreturn',
        'ali_public_key'    => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzBu++i8EwQf1DyXMboiRGqs78tuxlDOQTNJWGf1TvPavpLDwfI0oNkChIccBWzxrIsVFlQBxnI5az8sMKcY3YhEqiPcPTwdeqoooDNqSXJY6pR+7upqx5Gvo8X0JHx7cx4b0jhHz7dbERk8+kXTpLePw+RmUMkHiTNUDCfExU1y4bMrdzL7E8MzfH7yM+w35iSX2cmRt3Y7/NAOctQZXMl03QOTExUjGINejnDSygPb0JFkcMphtR8FnjdKWVbTeEpKDuonjafdewXK3vhdPtBp3bWfG8vfQeIYPA1/GuUBjOKdYzlYCXWFtjqC15dDEz158Xjfjmd00mBWcj1hWVwIDAQAB',
        'private_key'       => 'MIIEowIBAAKCAQEA68p/STKYwVMELyTYo8WuNDHjYTVRJOpcDmwiVyST/NfY30/Be2srGFtYHJyBzP8o6emLkwGFCBjx/SB/SQ8xpdb3H6KRqF9J39Su8TI8ae9qbQIZ12ijRL1L+JdhOQy3DlzXkXeDJMynyoiSEa+SiAO8AQM2+/Xw3fkjeybCAu79BZhVXZFGMN+v2D1Conyw/vI3N0G5V/BZFXPG3FDZc+iIVrT+Qe18ZWihZFNsn2nkmRrZJcJLPoxC8irblKgVUUxN+pMi/tGFlZm7NNwJPK/t+tUExFaQhJ1Y3oBfW460kiUcKN5tCl/DjEa5HOqE7CxhvTBhsxm41S0EtdRbLwIDAQABAoIBAG+TbxAQJUC2K/CzGuDEll6UjOhe9nrle5JHkShzYqPu7+0cLI5edBIeh19in/mFdLLblPSHb5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hvcMOTnwYVw2I6UtYSf++PzBw4r5Lkg0IC9UNaM9bQ5hR5Nn8'];

    //todo 微信
    protected static $wechat = [
        'app_id'            => 'wxb598cf50e9fdcb41', // APP APPID
        'mch_id'            => '1541729541',
        'key'               => 'Albinance1ba59abbe56e057f20f883e',
        'notify_url'        => 'http://www.aibinance.com/public/index.php/payback/wechat',
    ];

    //todo 支付宝回调
    public function notify()
    {
        $alipay = Pay::alipay(self::$alipay);
        $data = $alipay->verify(); // 是，验签就这么简单！;
      	if ($data['trade_status'] != 'TRADE_SUCCESS')return false;
        $map['number']    = $data['out_trade_no'];
        $map['status']    = 0;
        $have = Db::name('order')->where($map)->find();     	
        if(!$have)return false;
        $gear = Db::name('gear')->where(['id'=>$have['id']])->find();
        //if($data['buyer_pay_amount'] != $gear['price']) return false;
      	$time = Db::name('user_service')->where(['uid'=>$have['uid']])->value('expire');
      	if($time < time())$time = time();
        $service = ['vip'=>$gear['vip'],'expire'=>$time+$gear['expire']*86400];
        if($gear['expire'] == 0)$service['expire'] = 0;
        Db::startTrans();
        try{
            Db::name('order')->where($map)->update(['status'=>1,'pay_time'=>time()]);
          	$this->FirstChange($have['uid'],$gear['price'],$gear['vip']);
            Db::name('user_service')->where(['uid'=>$have['uid']])->update($service);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            cache('message',[$e->getMessage(),$e->getLine()]);
          	exit();
        }
        return $alipay->success()->send();
    }

    public function wechat()
    {
        $pay = Pay::wechat(self::$wechat);
        $verify = $pay->verify(); // 是的，验签就这么简单！
		$res =  Cache::set('w',$verify);
        if($verify['result_code'] != 'SUCCESS')return false;		
        $map['number']    = $verify['out_trade_no'];
        $map['status']    = 0;
        $order = Db::name('order')->where($map)->find();
        if(!$order)return false;
        $price = $verify['cash_fee']/100;
        //if($data['total_fee']*100 != $gear['price']) return false;
        $gear = Db::name('gear')->where(['id'=>$order['id']])->find();
      	$time = Db::name('user_service')->where(['uid'=>$order['uid']])->value('expire');
      	if($time < time())$time = time();
        $service = ['vip'=>$gear['vip'],'expire'=>$time+$gear['expire']*86400];
        if($gear['expire'] == 0)$service['expire'] = 0;
        Db::startTrans();	
        try{
            Db::name('order')->where($map)->update(['status'=>1,'pay_time'=>time()]);
          	$this->FirstChange($order['uid'],$gear['price'],$gear['vip']);
            Db::name('user_service')->where(['uid'=>$order['uid']])->update($service);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            cache('message',[$e->getMessage(),$e->getLine()]);exit();
        }
        return $pay->success()->send();
    }

  	public function FirstChange($uid,$price,$vip){
      	$prices = $price;
        $map = ['uid'=>$uid];
        $user = Db::name('user_service')
            ->where($map)
            ->find();
        $integral = 0;
        if($user['vip'] == 0){
            $integral +=  188;
          	if($integral != 0)$this->IntegralLog($uid,'首次订阅奖励','1',$integral);
          	$integral += $prices;
        }else{
        	if($vip == 1){
            	$integral +=  $price/2;
            	$price = $price/2;
        	}
        	if($vip == 2)$integral +=  $price;
        }
        $this->IntegralLog($uid,'订阅奖励',1,$price);
        Db::name('user')->where($map)->setInc('integral',$integral);
      	$this->GetPid($uid,$prices,$vip);
        return;
    }
  
  	public function GetPid($uid,$price,$vip){
        $user = Db::name('user')->where(['uid'=>$uid])->find();
        if($user['pid'] == 0)return false;
        $first = Db::name('user')->where(['uid'=>$user['pid']])->find();
        if(!$first)return false;
        $integral = 0;
        if($vip == 1)$integral = $price * 0.4;
        if($vip == 2)$integral = $price * 0.8;
        $this->IntegralLog($first['uid'],'一级好友订阅奖励',1,$integral);
        Db::name('user')->where(['uid'=>$first['uid']])->setInc('integral',$integral);
        if($first['pid'] != 0){
        $two = Db::name('user')->where(['uid'=>$first['pid']])->find();
        	if(!$two)return false;
        	$integral = 0;
       	 	if($vip == 1)$integral = $price * 0.1;
        	if($vip == 2)$integral = $price * 0.2;
        	$this->IntegralLog($first['pid'],'二级级好友订阅奖励',1,$integral);
        	Db::name('user')->where(['uid'=>$first['pid']])->setInc('integral',$integral);        		
        }
        
        return true;
    }
  	
  
    public function ddd(){
       $res =  cache('message');
     // $res =  Cache::get('message');
       var_dump($res);die;
    }
}